﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Text.RegularExpressions;

namespace LabelPrintSystem
{
    public partial class FrmMain : Form
    {
        public FrmMain(ClsDataUser user)
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            this.m_user = user;
            this.m_printInfo = new ClsPrintInfo();
        }

        ClsDataUser m_user;
        System.Threading.Timer m_time_now;
        ClsPrintInfo m_printInfo;
        ClsProcess m_process;
        clsProcessForAntennaPack m_clsProcessForAntennaPack;
        List<ClsTProductTypeInfo> m_TProductType;

        private bool isClosing = false; // Set to true if we are closing. This helps discontinue thumbnail loading.
        // Label browser
        private string[] browsingFormats; // The list of filenames in the current folder
        Hashtable listItems; // A hash table containing ListViewItems and indexed by format name.
        // It keeps track of what formats have had their image loaded.
        Queue<int> generationQueue; // A queue containing indexes into browsingFormats
        // to facilitate the generation of thumbnails

        // Label browser indexes.
        int topIndex; // The top visible index in the lstLabelBrowser
        int selectedIndex; // The selected index in the lstLabelBrowser

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //  m_time_now = new System.Threading.Timer(evt_timer_tick, null, 0, 1000);
            // Setup the images used in the label browser.
            lstLabelBrowser.View = View.LargeIcon;
            lstLabelBrowser.LargeImageList = new ImageList();
            lstLabelBrowser.LargeImageList.ImageSize = new Size(100, 100);
            lstLabelBrowser.LargeImageList.Images.Add(Properties.Resources.LoadingFormat);
            lstLabelBrowser.LargeImageList.Images.Add(Properties.Resources.LoadingError);
            // Initialize a list and a queue.
            listItems = new System.Collections.Hashtable();
            generationQueue = new Queue<int>();
            //Initialize 
            LoadIniFile();
            LoadFrm();
        }

        void LoadIniFile()
        {
            IniFile.SetFileName(Application.StartupPath + "\\Other.ini");
            this.m_printInfo.sTemplePath = IniFile.IniReadValue("TemplePath", "Path", @"D:\LabelTemple");
            this.m_printInfo.IsKeyPress = IniFile.IniReadValue("TemplePath", "IsKeyPress", "1") == "1" ? true : false;
            if (this.m_printInfo.IsKeyPress)
            {
                label2.Visible = nud_ProductSnLength.Visible = false;
            }
        }
        void LoadFrm()
        {
            string[] sArray = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString().Split(new char[1] { '.' });
            if (ClsDifinition.RUNNING_MODE == 1)
            {
                this.Text = string.Format("诺基亚车间标签打印软件{0}.{1}", sArray[0], sArray[1]);
                this.m_process = new ClsProcessForMOD(this.m_printInfo, this.m_user);
                免测配置ToolStripMenuItem1.Visible = cb_isAutoPrint.Visible = lbl_Status.Visible = nud_IdenticalCopies.Visible = btn_OpenForamt.Visible = cb_isSpecial_R_AAU.Visible = nokiaToolStripMenuItem.Visible = false;
                cb_Printer.Location = new Point(574, 13);
                tab_module.TabPages.Remove(tabPage2);
            }
            else
            {
                this.Text = string.Format("天线产品标签打印软件{0}.{1}", sArray[0], sArray[1]);
                this.m_process = new ClsProcessForANTENNA(this, this.m_printInfo, this.m_user);
                this.m_clsProcessForAntennaPack = new clsProcessForAntennaPack(this, this.m_printInfo.config);
                RenewDataSource();
                this.m_clsProcessForAntennaPack.ShowMsgevent += ShowMsg;
                cb_isAutoPrint.SelectedIndex = 0;
                lbl_Status.Text = string.Format("打印类型:常规产品");
            }
            this.toolStripStatusLabel2.Text = string.Format("设备IP:{0}      管理部门:质量&&制造", m_user.sEquID);
            toolStripStatusLabel3.Text = string.Format("员工号: {0}     账号类型: {1}", m_user.sUserID, m_user.sRemark);

            evt_book();
            this.m_process.getPrinters();
            txt_FocusSelect(txtProcuctSN);
            this.cb_Printer.DropDown += new System.EventHandler(Function.CbAutoFix);
            this.cb_isAutoPrint.DropDown += new System.EventHandler(Function.CbAutoFix);
            //  this.cb_ProductTypeID.DropDown += new System.EventHandler(Function.CbAutoFix);
            //Thread m_thread_getEngine = new Thread(m_getEngine);
            //m_thread_getEngine.IsBackground = true;
            //m_thread_getEngine.Start();
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            isClosing = true;

            // Make sure the thumbnail worker is stopped before we try closing BarTender or 
            // there might be problems in the worker.
            thumbnailCacheWorker.CancelAsync();
            while (thumbnailCacheWorker.IsBusy)
            {
                Application.DoEvents();
            };

            this.m_process.StopProcess();
            //// Quit the BarTender Print Engine, but do not save changes to any open formats.
            //if (engine != null)
            //    engine.Stop(SaveOptions.DoNotSaveChanges);
        }

        void evt_book()
        {
            this.m_process.evt_get_engine_handle += m_process_evt_get_engine_handle;
            this.m_process.evt_show_log_handle += m_process_evt_show_log_handle;
        }
        void m_process_evt_get_engine_handle(object sender, EventArgs e)
        {
            ClsPrintInfo printInfo = sender as ClsPrintInfo;
            if (printInfo.PrinterName != null)
                this.Invoke(new ThreadStart(delegate
                {
                    cb_Printer.Items.AddRange(printInfo.PrinterName.ToArray());
                    cb_Printer.SelectedItem = printInfo.DefaultPrinterName;
                }
                ));
        }
        void m_process_evt_show_log_handle(object sender, EventArgs e)
        {
            if (e == null)
            {
                this.Invoke(new ThreadStart(delegate
                {
                    txt_log.AppendText(sender as string + "\r\n");
                }));
                return;
            }
            ClsEventMode ee = e as ClsEventMode;
            if (ee.evt_mode == ClsEventMode.en_evtMode.evt_log)
            {
                this.Invoke(new ThreadStart(delegate
                {
                    txt_log.AppendText(sender as string + "\r\n");
                }));
            }
            else if (ee.evt_mode == ClsEventMode.en_evtMode.evt_err)
            {
                this.Invoke(new ThreadStart(delegate
                {
                    txt_log.AppendText(sender as string + "\r\n打印终止\r\n");
                    Tips(sender as string, 0);
                    setControlEnable(true);
                    txt_FocusSelect(txtProcuctSN);
                }));
            }
            else if (ee.evt_mode == ClsEventMode.en_evtMode.evt_get_temple)
            {
                browsingFormats = sender as string[];
                if (browsingFormats != null)
                    this.Invoke(new ThreadStart(delegate
                    {
                        lstLabelBrowser.VirtualListSize = browsingFormats.Length;
                    }));
            }
            else if (ee.evt_mode == ClsEventMode.en_evtMode.evt_complete)
            {
                this.Invoke(new ThreadStart(delegate
                {
                    txt_log.AppendText(sender as string + "\r\n打印终止\r\n");
                    setControlEnable(true);
                    txt_FocusSelect(txtProcuctSN);
                }));
            }
            else if (ee.evt_mode == ClsEventMode.en_evtMode.evt_update_lb)
            {
                this.Invoke(new ThreadStart(delegate
                {
                    lbl_Status.Text = sender as string;
                }));
            }
            else if (ee.evt_mode == ClsEventMode.en_evtMode.evt_Tips)
            {
                this.Invoke(new ThreadStart(delegate
                {
                    Tips(sender as string, 0);
                }));
            }
        }

        void m_getEngine()
        {
            FrmTips ctl_frm_message = new FrmTips("加载进程中，请耐心等候.....");
            this.Invoke(new ThreadStart(delegate
            {
                this.Cursor = Cursors.WaitCursor;
                txtProcuctSN.Enabled =
                      panel1.Enabled = false;
                ctl_frm_message.Show();
            }));
            try
            {
                if (!this.m_process.getEngine())
                {
                    Application.Exit();
                    //return;
                }
                else
                {
                    this.Invoke(new ThreadStart(delegate
                    {
                        this.Cursor = Cursors.Arrow;
                        txtProcuctSN.Enabled =
                              panel1.Enabled = true;
                        ctl_frm_message.Close();
                        ctl_frm_message = null;
                    }));
                }
            }
            catch (Exception ee)
            {
                Tips(ee.ToString(), 0);
                return;
            }
        }

        #region tips
        private bool ShowMsg(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((Action)(() => { txt_PackLog.AppendText(msg + "\r\n"); }));
                return true;
            }
            else
            {
                txt_PackLog.AppendText(msg + "\r\n");
                return false;
            }
        }
        public bool Tips(string text, int btn = 1)
        {
            bool ret = false;
            this.Invoke(new ThreadStart(delegate
            {
                MessageBoxButtons msgBtn = btn == 1 ? MessageBoxButtons.OKCancel : MessageBoxButtons.OK;
                if (MessageBox.Show(text, "提示", msgBtn, MessageBoxIcon.Exclamation) == DialogResult.OK)
                {//重新开始
                    ret = true;
                }
                else
                {
                    ret = false;
                }
            }));
            return ret;
        }
        #endregion
        #region
        static Regex reUnicode = new Regex(@"\\u([0-9a-fA-F]{4})", RegexOptions.Compiled);
        public static string Decode(string s)
        {
            return reUnicode.Replace(s, m =>
            {
                short c;
                if (short.TryParse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture, out c))
                {
                    return "" + (char)c;
                }
                return m.Value;
            });
        }
        #endregion

        void evt_timer_tick(object sender)
        {
            // this.toolStripStatusLabel5.Text = DateTime.Now.ToShortTimeString(); //DateTime.Now.ToLongTimeString();
        }

        void setControlEnable(bool bl = false)
        {
            panel1.Enabled = lstLabelBrowser.Enabled = bl;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {//追溯
            if (!this.m_process.BlGetEngine)
            {
                m_getEngine();
            }
            if (txtProcuctSN.Text.Trim() == "")
            {
                Tips("请输入产品SN!", 0);
                txt_FocusSelect(txtProcuctSN);
                return;
            }
            txt_log.Text = "";
            m_printInfo.config.isSpecial_R_AAU = cb_isSpecial_R_AAU.Checked;
            if (this.m_process.ToSettingSN(string.Format(txtProcuctSN.Text.Trim().ToUpper())))
            {

                setControlEnable(false);
                browsingFormats = null;
                lstLabelBrowser.VirtualListSize = 0;
                this.m_printInfo.SelectPrinterName = cb_Printer.SelectedItem.ToString();
                this.m_printInfo.IdenticalCopies = nud_IdenticalCopies.Value.ToString();
                this.m_printInfo.TemType = cb_isAutoPrint.SelectedIndex;
                this.m_process.StartProcess();
            }
        }
        private void btn_manual_Click(object sender, EventArgs e)
        {
            if (txtProcuctSN.Text.Trim() == "")
            {
                Tips("请输入产品SN!", 0);
                txt_FocusSelect(txtProcuctSN);
                return;
            }
            txt_log.Text = "";
            m_printInfo.config.isSpecial_R_AAU = cb_isSpecial_R_AAU.Checked;

            if (this.m_process.ToSettingSN(string.Format(txtProcuctSN.Text.Trim().ToUpper())))
            {
                if (lstLabelBrowser.SelectedIndices.Count == 1)
                {
                    txt_log.AppendText("\r\n手动打印\r\n");
                    setControlEnable(false);
                    this.m_printInfo.SelectPrinterName = cb_Printer.SelectedItem.ToString();
                    this.m_printInfo.IdenticalCopies = nud_IdenticalCopies.Value.ToString();
                    this.m_process.LoadFormat(selectedIndex = lstLabelBrowser.SelectedIndices[0]);
                }
                else
                {
                    Tips("未选中打印模板", 0);
                }
            }
        }
        private void btn_OpenForamt_Click(object sender, EventArgs e)
        {
            if (lstLabelBrowser.SelectedIndices.Count == 1)
            {
                //this.m_process.EngineVisible(true, selectedIndex = lstLabelBrowser.SelectedIndices[0]);
                this.m_process.OpenLabelFormat(selectedIndex = lstLabelBrowser.SelectedIndices[0]);
            }
            else
            {
                Tips("未选中模板", 0);
            }
        }
        private void txtProcuctSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.m_printInfo.IsKeyPress && e.KeyChar == 13)
            {
                btnOK.PerformClick();
            }
        }
        private void txtProcuctSN_TextChanged(object sender, EventArgs e)
        {
            if (!this.m_printInfo.IsKeyPress && txtProcuctSN.TextLength == nud_ProductSnLength.Value)
            {//天线条码为19或23位
                btnOK.PerformClick();
            }
        }
        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmChangePwd frmpwd = new FrmChangePwd(this.m_user);
            frmpwd.ShowDialog();
        }
        private void 管理用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.m_user.HavePower(clsPowerManage.power.admin))
            {
                MessageBox.Show("权限不足！");
                return;
            }
            //FrmLogin frmlogin = new FrmLogin(this.m_user);
            //if (frmlogin.ShowDialog() == DialogResult.OK)
            //{
            FrmPowManage frmpowmanage = new FrmPowManage(this.m_user.aUser);
            frmpowmanage.ShowDialog();
            //this.OnShown(e);
            //}
        }
        private void 免测配置ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (!this.m_user.HavePower(clsPowerManage.power.config))
            {
                MessageBox.Show("权限不足！");
                return;
                //ClsDataUser aUser = new ClsDataUser();
                //FrmLogin frmlogin = new FrmLogin(aUser);
                //if (frmlogin.ShowDialog() != DialogResult.OK)
                //{
                //    return;
                //}
            }
            FrmUncheckConfig config = new FrmUncheckConfig(this.m_printInfo.config);
            if (config.ShowDialog() == DialogResult.OK)
            {
                string lbstatus = "";
                if (m_printInfo.config.setModule == (int)ClsConfig.SetModule.normal)
                {
                    lbstatus = "类型:常规产品";
                }
                else if (m_printInfo.config.setModule == (int)ClsConfig.SetModule.reform)
                {
                    lbstatus = string.Format("类型:改造产品,改造数量:{0}", m_printInfo.config.numReform);
                }
                else if (m_printInfo.config.setModule == (int)ClsConfig.SetModule.uCheck)
                {
                    lbstatus = string.Format("类型:免测产品,交调数量:{0},电性能数量{1},RCU数量{2}", m_printInfo.config.numPIM, m_printInfo.config.numElectric, m_printInfo.config.numRcu);
                }
                lbl_Status.Text = lbstatus;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            FrmLabelPrint labelprint = new FrmLabelPrint();
            labelprint.ShowDialog(this);
        }

        #region Enumerations
        // Indexes into our image list for the label browser.
        enum ImageIndex { LoadingFormatImage = 0, FailureToLoadFormatImage = 1 };
        #endregion

        #region Thumbnail Event Handlers
        /// <summary>
        /// Called when a thumbnail was loaded so it can be shown.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void thumbnailCacheWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            object[] args = e.UserState as object[];
            ListViewItem item = (ListViewItem)args[0];

            // 100 means we got the image successfully.
            if (e.ProgressPercentage == 100)
            {
                Image thumbnail = (Image)args[1];

                lstLabelBrowser.LargeImageList.Images.Add(item.Text, thumbnail);
                item.ImageIndex = lstLabelBrowser.LargeImageList.Images.IndexOfKey(item.Text);
            }
            else if (e.ProgressPercentage == 0) // 0 means we did not successfully get the format image.
            {
                item.ImageIndex = (int)ImageIndex.FailureToLoadFormatImage;
            }
            item.ListView.Invalidate(item.Bounds);
        }

        /// <summary>
        /// Loads thumbnails in a background thread so the UI doesn't hang.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void thumbnailCacheWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;

            int index;
            string fileName;

            // Loop until the queue of items that need to be loaded is empty or the worker was cancelled.
            while ((generationQueue.Count > 0) && !worker.CancellationPending && !isClosing)
            {
                lock (generationQueue)
                {
                    // Get the index to use.
                    index = generationQueue.Dequeue();
                }

                // If this is way out of our view don't bother generating it.
                if (Math.Abs(index - topIndex) < 30)
                {
                    fileName = browsingFormats[index];

                    // Check to see if the listitem is already generated and just waiting for a thumbnail.
                    ListViewItem item = (ListViewItem)listItems[fileName];
                    if (item == null)
                    {
                        item = new ListViewItem(fileName);
                        item.ImageIndex = (int)ImageIndex.LoadingFormatImage;
                        listItems.Add(fileName, item);
                    }

                    // If the listitem doesn't already have a thumbnail, generate it.
                    if (item.ImageIndex == (int)ImageIndex.LoadingFormatImage)
                    {
                        try
                        {
                            Image btwImage = Seagull.BarTender.Print.LabelFormatThumbnail.Create(fileName, Color.Gray, 100, 100);

                            object[] progressReport = new object[] { item, btwImage };
                            worker.ReportProgress(100, progressReport);//引发 System.ComponentModel.BackgroundWorker.ProgressChanged 事件。
                        }
                        // If the file isn't an actual btw format file we will get an exception.
                        catch
                        {
                            object[] progressReport = new object[] { item, null };
                            worker.ReportProgress(0, progressReport);
                        }
                    }
                }
            }
        }
        #endregion

        #region List View Event Handlers
        /// <summary>
        /// Called when the user clicks on an item in the format browser.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstLabelBrowser_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstLabelBrowser.SelectedIndices.Count == 1)
            {
                selectedIndex = lstLabelBrowser.SelectedIndices[0];
                //EnableControls(false);
                //picUpdatingFormat.Visible = true;

                //// Start a BackgroundWorker to load the format to extract the copies
                //// data and substrings. Then update the UI with the data.
                //BackgroundWorker formatLoader = new BackgroundWorker();
                //formatLoader.DoWork += new DoWorkEventHandler(formatLoader_DoWork);
                //formatLoader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(formatLoader_RunWorkerCompleted);
                //formatLoader.RunWorkerAsync(selectedIndex);
            }
            else if (lstLabelBrowser.SelectedIndices.Count == 0)
            {
                //EnableControls(false);
                //picUpdatingFormat.Visible = false;
            }
        }
        /// <summary>
        /// Called when the format browser listbox scrolls a listitem into view.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstLabelBrowser_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            int btwFileIndex = e.ItemIndex;

            // If our list doesn't have this item then add it and set the
            // image index to "loading" so that the image will be loaded.
            if (listItems[browsingFormats[btwFileIndex]] == null)
            {
                e.Item = new ListViewItem(browsingFormats[btwFileIndex]);
                e.Item.ImageIndex = (int)ImageIndex.LoadingFormatImage;
                listItems.Add(browsingFormats[btwFileIndex], e.Item);
            }
            else
            {
                e.Item = (ListViewItem)listItems[browsingFormats[btwFileIndex]];
            }

            // Add the index to the queue so that the thumbnail thread can get the image.
            if (e.Item.ImageIndex == (int)ImageIndex.LoadingFormatImage)
            {
                lock (generationQueue)
                {
                    if (!generationQueue.Contains(btwFileIndex))
                        generationQueue.Enqueue(btwFileIndex);
                }
            }

            // If we put anything on the queue, start the thumbnail worker if it's not already started.
            if (!thumbnailCacheWorker.IsBusy && (generationQueue.Count > 0))
            {
                thumbnailCacheWorker.RunWorkerAsync();
            }
        }

        /// <summary>
        /// Called when the format browser listbox needs to cache listitems that may appear soon.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="cacheEvent"></param>
        private void lstLabelBrowser_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs cacheEvent)
        {
            topIndex = cacheEvent.StartIndex;

            lock (generationQueue)
            {
                for (int index = cacheEvent.StartIndex; index <= cacheEvent.EndIndex; ++index)
                {
                    ListViewItem listViewItem = (ListViewItem)listItems[browsingFormats[index]];

                    if ((listViewItem != null) && (listViewItem.ImageIndex == (int)ImageIndex.LoadingFormatImage))
                    {
                        if (!generationQueue.Contains(index))
                            generationQueue.Enqueue(index);
                    }
                }
            }

            // If we put anything on the queue, start the thumbnail worker if it's not already started.
            if (!thumbnailCacheWorker.IsBusy && (generationQueue.Count > 0))
            {
                thumbnailCacheWorker.RunWorkerAsync();
            }
        }
        #endregion

        private void lstLabelBrowser_DoubleClick(object sender, EventArgs e)
        {
            btn_OpenForamt_Click(sender, e);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.toolStripStatusLabel5.Text = DateTime.Now.ToShortTimeString(); //DateTime.Now.ToLongTimeString();
        }

        private void cb_ProductTypeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_ProductTypeID.DataSource == null) return;
            clearSN();
            setEnable();
            //setFocus();
            ClsPackConfigInfo info = m_clsProcessForAntennaPack.getPackConfig(((ClsTProductTypeInfo)cb_ProductTypeID.SelectedItem).ProductTypeID);
            if (info == null)
                return;
            lbl_RetrospectSN.Enabled = txt_RetrospectSN.Enabled = info.RSN;
            lbl_ALDSN.Enabled = txt_ALDSN.Enabled = info.ALDSN;
            lbl_ProductSN.Enabled = txt_ProductSN.Enabled = info.PSN;
            lbl_ProductCode.Enabled = txt_ProductCode.Enabled = info.TBC;
            lbl_OutsideBSN.Enabled = txt_OutsideBSN.Enabled = info.OBSN;
            lbl_OutsideBCode.Enabled = txt_OutsideBCode.Enabled = info.BTBC;
            lbl_OutsideCSN.Enabled = txt_OutsideCSN.Enabled = info.OCSN;
            lbl_OutsideCSN1.Enabled = txt_OutsideCSN1.Enabled = info.OCSN1;
            lbl_OutsideCSN2.Enabled = txt_OutsideCSN2.Enabled = info.OCSN2;
            lbl_OutsideCSN3.Enabled = txt_OutsideCSN3.Enabled = info.OCSN3;
            lbl_PCodeRule.Text = "规则: " + info.PCodeRule.ToString();
            txt_PackLog.Text = string.Format("规则描述：{0}\r\n", info.PCodeRuleRemark);
            //setFocus();
            //if (((ClsTProductTypeInfo)cb_ProductTypeID.SelectedItem).IsReviewCode == (int)ClsTProductTypeInfo.emReviewCode.IsReviewCode)
            //{
            //    lbl_RetrospectSN.Enabled = txt_RetrospectSN.Enabled = true;
            //}
            //else
            //{
            //    lbl_RetrospectSN.Enabled = txt_RetrospectSN.Enabled = false;
            //}
        }

        private void tab_module_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (tab_module.SelectedIndex == 1 && m_TProductType == null)
            //{//包装信息模式下,加载产品代码
            //    cb_ProductTypeID.Items.Clear();
            //    m_TProductType = m_clsProcessForAntennaPack.getTProductType();
            //    cb_ProductTypeID.DataSource = m_TProductType;
            //    cb_ProductTypeID.DisplayMember = ClsTProductTypeInfo.ProductTypeIDName;
            //}
        }
        void clearSN()
        {
            txt_RetrospectSN.Text = txt_ALDSN.Text =
            txt_ProductSN.Text = txt_ProductCode.Text =
            txt_OutsideBSN.Text = txt_OutsideBCode.Text =
            txt_OutsideCSN.Text = txt_OutsideCSN1.Text = txt_OutsideCSN2.Text = txt_OutsideCSN3.Text = string.Empty;
            txt_PackLog.Text = "";           
        }
        void setEnable()
        {
            lbl_RetrospectSN.Enabled = txt_RetrospectSN.Enabled = true;
            lbl_ALDSN.Enabled = txt_ALDSN.Enabled = true;
            lbl_ProductSN.Enabled = txt_ProductSN.Enabled = true;
            lbl_ProductCode.Enabled = txt_ProductCode.Enabled = true;
            lbl_OutsideBSN.Enabled = txt_OutsideBSN.Enabled = true;
            lbl_OutsideBCode.Enabled = txt_OutsideBCode.Enabled = true;
            lbl_OutsideCSN.Enabled = txt_OutsideCSN.Enabled = true;
            lbl_OutsideCSN1.Enabled = txt_OutsideCSN1.Enabled = true;
            lbl_OutsideCSN2.Enabled = txt_OutsideCSN2.Enabled = true;
            lbl_OutsideCSN3.Enabled = txt_OutsideCSN3.Enabled = true;
            lbl_PCodeRule.Text = "规则: ?";
        }
        void setFocus()
        {
            int txtId = int.MaxValue;
            foreach (Control ctl in gb_PackInfo.Controls)
            {
                if (ctl is TextBox && ctl.Enabled)
                {
                    if (ctl.TabIndex < txtId)
                    {
                        txtId = ctl.TabIndex;
                        txt_FocusSelect((TextBox)ctl);
                    }
                }
            }
        }
        void txt_FocusSelect(TextBox t)
        {
            t.Focus();
            t.SelectAll();
        }
        void RenewDataSource()
        {//包装信息模式下,加载产品代码     
            this.BeginInvoke(new ThreadStart(delegate
            {
                cb_ProductTypeID.DataSource = null;
                cb_ProductTypeID.Items.Clear();
                if (m_TProductType != null)
                    m_TProductType.Clear();
                m_TProductType = m_clsProcessForAntennaPack.getTProductType();
                cb_ProductTypeID.DataSource = m_TProductType;
                cb_ProductTypeID.DisplayMember = ClsTProductTypeInfo.ProductTypeIDName;
            }));
        }

        void keyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                TextBox tb = sender as TextBox;
                int icount = 0;
                List<int> li = new List<int>();
                foreach (Control ctl in gb_PackInfo.Controls)
                {
                    if (ctl is TextBox && ctl.Enabled)
                    {
                        li.Add(ctl.TabIndex);
                    }
                    if (++icount == gb_PackInfo.Controls.Count)
                    {
                        li.Sort();
                        if (li.IndexOf(tb.TabIndex) == li.Count - 1)
                        {
                            btn_Pack.PerformClick();
                            foreach (Control ct in gb_PackInfo.Controls)
                            {
                                if (ct is TextBox && ct.TabIndex == li[0])
                                {
                                    txt_FocusSelect((TextBox)ct);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            foreach (Control ct in gb_PackInfo.Controls)
                            {
                                if (ct is TextBox && ct.TabIndex == li[li.IndexOf(tb.TabIndex) + 1])
                                {
                                    txt_FocusSelect((TextBox)ct);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        private void btn_Pack_Click(object sender, EventArgs e)
        {
            //    if (((ClsTProductTypeInfo)cb_ProductTypeID.SelectedItem).IsReviewCode == (int)ClsTProductTypeInfo.emReviewCode.IsReviewCode)
            //    {
            //        if (txt_RetrospectSN.Text.Trim() == string.Empty ||
            //            txt_ProductSN.Text.Trim() == string.Empty ||
            //            txt_OutsideBSN.Text.Trim() == string.Empty
            //            )
            //        {
            //            Tips("条码不能为空", 0);
            //            return;
            //        }
            //    }
            //    else
            //    {
            //        if (txt_ProductSN.Text.Trim() == string.Empty ||
            //            txt_OutsideBSN.Text.Trim() == string.Empty
            //           )
            //        {
            //            Tips("条码不能为空", 0);
            //            return;
            //        }
            //    }

            foreach (Control ctl in gb_PackInfo.Controls)
            {
                if (ctl is TextBox && ctl.Enabled && ctl.Text == string.Empty)
                {
                    Tips("条码不能为空", 0);
                    setFocus();
                    return;
                }
            }
            txt_PackLog.Text = "";

            ClsPackInfo packinfo = new ClsPackInfo();
            packinfo.ProductTypeID = ((ClsTProductTypeInfo)cb_ProductTypeID.SelectedItem).ProductTypeID;
            packinfo.RetrospectSN = txt_RetrospectSN.Text.Trim();
            packinfo.ProductSN = txt_ProductSN.Text.Trim();
            packinfo.OutsideBSN = txt_OutsideBSN.Text.Trim();
            packinfo.OutsideCSN = txt_OutsideCSN.Text.Trim();
            packinfo.TBC = txt_ProductCode.Text.Trim();
            packinfo.BTBC = txt_OutsideBCode.Text.Trim();
            packinfo.OCSN1 = txt_OutsideCSN1.Text.Trim();
            packinfo.OCSN2 = txt_OutsideCSN2.Text.Trim();
            packinfo.OCSN3 = txt_OutsideCSN3.Text.Trim();
            packinfo.ALDSN = txt_ALDSN.Text.Trim();
            packinfo.PCIP = m_user.sEquID;
            packinfo.PackageUser = m_user.sUserID;
            packinfo.PackageTime = DateTime.Now;
            ClsRelevanceInfo reinfo = new ClsRelevanceInfo();
            reinfo.RetrospectSN = packinfo.RetrospectSN;
            reinfo.ProductSN = packinfo.ProductSN;
            reinfo.PCIP = m_user.sEquID;
            reinfo.RelevanceUser = m_user.sUserID;
            reinfo.RelevanceTime = packinfo.PackageTime;

            //m_clsProcessForAntennaPack.ToSetting(packinfo, reinfo, (ClsTProductTypeInfo)cb_ProductTypeID.SelectedItem);
            if (m_clsProcessForAntennaPack.ToSetting(packinfo, reinfo))
            {
                m_clsProcessForAntennaPack.ToStratProcess();
                clearSN();
            }
            setFocus();
            //if (((ClsTProductTypeInfo)cb_ProductTypeID.SelectedItem).IsReviewCode == (int)ClsTProductTypeInfo.emReviewCode.IsReviewCode)
            //{
            //    txt_FocusSelect(txt_RetrospectSN);
            //}
            //else
            //{
            //    txt_FocusSelect(txt_ProductSN);
            //}

        }

        private void btn_Renew_Click(object sender, EventArgs e)
        {
            RenewDataSource();
        }

        private void nokiaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmConfig frm = new FrmConfig(ClsDifinition.key1ForANTENNA, ClsDifinition.key2ForANTENNA, m_printInfo.config.sNokia, m_printInfo.config.isNokia, m_printInfo.config.isCheckQrCode);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ClsDifinition.key1ForANTENNA = frm.txtBarCode.Text.Trim();
                ClsDifinition.key2ForANTENNA = frm.txtQrCode.Text.Trim();
                m_printInfo.config.sNokia = frm.txtNokia.Text.Trim();
                m_printInfo.config.isNokia = frm.cbNokia.Checked;
                m_printInfo.config.isCheckQrCode = frm.ckQrCode.Checked;
            }
            frm.Dispose();
        }

    }


}
